﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
using Word = NetOffice.WordApi;
using NetOffice.WordApi.Enums;

namespace WordCrossRefAddin {

    public partial class CrossRefList : UserControl {

        public readonly Word.Application WordApp;
        public readonly Word.Window WordWindow;
        readonly RefListProp _Prop;

        public CrossRefList(RefListProp prop) {

            InitializeComponent();
            this.WordApp = Addin.Core.WordApp;
            this.WordWindow = Addin.Core.WordApp.ActiveWindow;

            _Prop = prop;
        }

        // sec: functions
        
        public void InsertCrossRefs() {

            var app = this.WordApp;
            foreach (int i_sel in _UINumTitleList.SelectedIndices) {

                app.Selection.InsertCrossReference(
                   _Prop.RefType,
                   _Prop.RefKind, // 章番号にはwdNumberNoContext
                   i_sel + 1);
            }

            app.ActiveWindow.SetFocus(); // 挿入後にすぐタイプできる、操作性を向上
        }

        public void RefreshRefList() {

            _UINumTitleList.SuspendLayout(); // ちらつき防止

            var doc = this.WordApp.ActiveDocument;
            var items_raw = doc.GetCrossReferenceItems(_Prop.RefType);
            var items_arr = items_raw as Array; // HACK: 2段階で変換するとうまくいく
            var items_iter = items_arr as System.Collections.IEnumerable;

            _UINumTitleList.Items.Clear();
            foreach (string item in items_iter) {
                _UINumTitleList.Items.Add(item);
            }

            _UINumTitleList.Columns[0].Text = string.Format("番号とタイトル ({0}個)", _UINumTitleList.Items.Count);

            _UINumTitleList.ResumeLayout(false); // 処理の末尾に配置
        }

        // sec: GUI events

        private void CrossRefPane_Load(object sender, EventArgs e) {

            if (this.DesignMode)
                return;

            this.RefreshRefList();
        }

        private void _UIInsertCrossRef_ButtonClick(object sender, EventArgs e) {
            this.InsertCrossRefs();
        }

        private void _UIUpdateCrossRefList_Click(object sender, EventArgs e) {
            this.RefreshRefList();
        }

        private void _UISyncroCrossRefItem_Click(object sender, EventArgs e) {

        }
    }
}